package main

import (
	"fmt"
	"log"
	"net/http"
	"path"

	"github.com/gin-gonic/gin"
)

/*
文件上传
*/
func main() {
	router := gin.Default()
	//为multipart forms 设置较低的内存限制（默认32Mib）
	router.MaxMultipartMemory = 8 << 20 // 8 MiB
	//单文件上传
	router.POST("/upload", func(c *gin.Context) {
		//单文件
		file, err := c.FormFile("file")
		if err != nil {
			fmt.Println("上传失败,", err)
			return
		}
		log.Println(file.Filename)
		//上传文件至指定目录  file.Filename为文件名称
		dst := path.Join("../static/upload", file.Filename)
		c.SaveUploadedFile(file, dst)
		c.JSON(http.StatusOK, gin.H{
			"status": "ok",
			"name":   file.Filename,
			"url":    dst,
		})
	})

	//多文件上传
	router.POST("/uploads", func(c *gin.Context) {
		//同名
		form, err := c.MultipartForm()
		if err != nil {
			fmt.Println("上传失败,", err)
			return
		}
		files := form.File["file"]
		for _, file := range files {
			log.Println(file.Filename)
			dst := path.Join("../static/upload", file.Filename)
			c.SaveUploadedFile(file, dst)
		}
		c.JSON(http.StatusOK, gin.H{
			"files": files,
		})

	})
	//不同名
	/* router.POST("/uploads", func(c *gin.Context) {
		file, err := c.FormFile("file")
		if err != nil {
			fmt.Println("上传失败,", err)
			return
		}
		dst := path.Join("../static/upload", file.Filename)
		c.SaveUploadedFile(file, dst)
		file2, err2 := c.FormFile("file2")
		if err2 != nil {
			fmt.Println("上传失败,", err2)
			return
		}
		dst2 := path.Join("../static/upload", file2.Filename)
		c.SaveUploadedFile(file2, dst2)
		c.JSON(http.StatusOK, gin.H{
			"status":    "ok",
			"fileName":  file.Filename,
			"fileName2": file2.Filename,
			"url":       dst,
		})
	}) */

	router.Run(":9000")

}
